package cn.edu.nuc.thrid.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.nuc.thrid.model.User;
import cn.edu.nuc.thrid.services.interfaces.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService service;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String userLogin1() {

		return "login/login";
	}

	/**
	 * 用户登录
	 * 
	 * @param user
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String userLogin2(@Valid @ModelAttribute("u") User user, Errors errors, HttpSession session, Model model) {

		/**/
		if (errors.hasErrors()) {
			return "login/login";
		}
		User u = service.login(user.getZybusername(), user.getZybuserpwd());
		session.setAttribute("u", u);
		if (u != null && u.getZybuserid() == -1) {

			return "redirect:/goods/adminpagelist";
		} else if (u != null && u.getZybuserid() != -1) {

			return "redirect:/user/userpagelist";
		}

		else {

			model.addAttribute("error", "账号或者密码错误");
			return "login/login";
		}
	}

	@RequestMapping("/regist")
	public String regist() {

		return "login/regist";
	}

	@RequestMapping(value = "/adduser", method = RequestMethod.POST)
	public String addUser(@Valid User user, Errors errors, Model model) {

		if (errors.hasErrors()) {
			System.out.println("注册校验");
			return "login/regist";
		}
		Integer result = service.regist(user);

		if (result > 0) {

			model.addAttribute("registsucc", "注册成功请登录！");
			return "login/login";
		} else if (result == -1) {
			model.addAttribute("registerror", "服务器忙，注册失败！");
			return "login/regist";
		} else {

			model.addAttribute("registerror", "服务器忙，注册失败！");
			return "login/regist";
		}
	}

	@RequestMapping(value = "/vali", method = RequestMethod.POST)
	public @ResponseBody String valiname(String zybusername) {

		// System.out.println("haha");
		String mes = service.valiname(zybusername);
		return mes;
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest req, HttpServletResponse resp) {

		HttpSession session = req.getSession();

		session.removeAttribute("u");
		
		return "redirect:/login";
	}
}
